import threading
import uuid
import pyautogui
import sys
import mwindow
import datetime
import time
import sched
from pynput.keyboard import Controller, Key, Listener
import skillmanager
import win32gui
import win32con
import tkinter as tk  
from tkinter import messagebox 

def on_press(key):
    # try:
    #     print("正在按压:", format(key.char))
    # except AttributeError:
    #     print("正在按压2:", format(key))
    if(key.char == 'q'):
        return False

def DragMouse(x1:int,y1:int,x2:int,y2:int,sec:int):
    pyautogui.moveTo(x1, y1)
    pyautogui.dragTo(x2, y2, sec, button='left')
    # pyautogui.mouseDown(x1, y1, button='left')
    # pyautogui.moveTo(x2, y2)
    # pyautogui.mouseUp(button='left') 

def ontimer(mainwin,mset : mwindow.MWindowSet,sm:skillmanager.SkillManager,op_state,isOnlyOnce):
    if mainwin.box.left < -32000:
        print("窗口小于-30000")
        sys.exit(0)
    print(f'ontimer: op_state={op_state}')
    win = mset.CheckWindow()
    if win != None:
        if win.name == "主界面-战斗":
            win.ClickLabel("进入游戏")
            # if op_state == 0:
            #     DragMouse(win.region[0] + 94, win.region[1] + 384,win.region[0] + 348, win.region[1] + 384,0.5)
            #     op_state = 2
            # elif op_state == 1:
            #     DragMouse(win.region[0] + 348, win.region[1] + 384, win.region[0] + 94, win.region[1] + 384,0.5)
            #     op_state = 2
            # else:
            #     num = win.GetLabelText('体力数目')
            #     if (num == None or not num.isdigit()) or int(num) >= 7:
            #         win.ClickLabel(index=0)
            # if op_state == 0 or op_state == 1:
            #     # for i in range(6):
            #     #     DragMouse(win.region[0] + 94, win.region[1] + 384,win.region[0] + 348, win.region[1] + 384,0.5)
            #     op_state = 2
            # else:
            #     num = win.GetLabelText('体力数目')
            #     if (num == None or not num.isdigit()) or int(num) >= 7:
            #         win.ClickLabel(index=0)
        elif win.name == "购买体力":
            print('购买体力')
            win.ClickLabel('免费获取')
            win.ClickLabel('继续')
        elif win.name == "游戏中":
            print('游戏中')
            if win.ExistLabel('技能中'):
                text1 = win.GetLabelText('技能识别1')
                text2 = win.GetLabelText('技能识别2')
                text3 = win.GetLabelText('技能识别3')
                skills = [text1,text2,text3]
                print(f'技能中,{skills}')
                choose,new_skillname = sm.Choose(skills)
                print(f'选择{choose}')
                if len(new_skillname) > 0:
                    print(f'写入新技能名称：{new_skillname}')
                    img = pyautogui.screenshot()
                    img.save(f'capture/new_{new_skillname}_{uuid.uuid1()}.png')
                win.ClickLabel(['技能识别1','技能识别2','技能识别3'][choose])
            if win.ExistLabel('转盘中'):
                print('转盘中')
                win.ClickLabel('跳过')
        elif win.name == "获得奖励":
            print('获得奖励')
            if isOnlyOnce:
                sys.exit(0)
            elif win.ExistLabel('获得奖励'):
                print('确认中')                                                                                                                                       
                win.ClickLabel('双倍')
                win.ClickLabel('确认')
        elif win.name == "广告":
            text = win.GetLabelText('已获得奖励')
            if text in ['已获得奖励','已获得奖状','已获得奖成']:
                win.ClickLabel("关闭")
                win.ClickLabel("点击屏幕继续")
    loop_monitor(op_state,isOnlyOnce)
def loop_monitor(op_state,isOnlyOnce):
    timer=threading.Timer(5,ontimer,args=[mainwin,mset,skillManager,op_state,isOnlyOnce])
    timer.start()    

def GetMainWnd():
    hwnd = win32gui.FindWindow('Chrome_WidgetWin_0', '国王指意')    
    if hwnd == None:
        return False
    windows = pyautogui.getWindowsWithTitle("国王指意")
    mainwin = None
    for w in windows:
        if w._hWnd == hwnd:
            mainwin = w
            break
    return mainwin

if __name__ == "__main__":
    pyautogui.PAUSE = 2.5
    pyautogui.FAILSAFE = True
    op_state = 2 #0-上一次失败 1-上一次胜利 2-已拖移关卡 
    print("start")
    isOnlyOnce = messagebox.askyesno("选项", "是否只执行一次?")  
    skillManager = skillmanager.SkillManager('skill.txt','skilllevel.txt')
    mainwin = GetMainWnd()
    if mainwin == None:
        print("没有找到")
        sys.exit(0)
    mainwin.move(0,0)
    # win32gui.BringWindowToTop(hwnd)
    mainwin.activate()
    if mainwin.box.left < -32000:
        print("窗口小于-30000")
        sys.exit(0)

    # 初始化窗口集合
    mset = mwindow.MWindowSet((mainwin.box.left,mainwin.box.top,mainwin.box.width,mainwin.box.height))
    mset.Load('国王指意.mset')

    # with Listener(on_press=on_press) as listener:
    #     listener.join()        
    loop_monitor(op_state,isOnlyOnce)
